package com.tlb.ejb;


import com.tlb.dto.Message;
import java.util.*;
import javax.persistence.*;


public class MessageDAO {
    private static com.tlb.web.Util util = com.tlb.web.Util.getUtil();
    public MessageDAO() {
    }
    
        
    public Message getMessageById(int messageId) {
        try {
            EntityManager em = util.getPersistenceFactory().createEntityManager();
            EntityTransaction tx = em.getTransaction();
            tx.begin();
            
            Message m = (Message)(em.createQuery(
                    "select m from Message m where messageId = :messageId"
                    )
                    .setParameter("messageId", messageId)
                    .getSingleResult());
            
            tx.commit();
            em.close();
            
            return m;
            
        } catch(Exception e) {
            System.err.println("Error getting message by id: " + messageId);
            e.printStackTrace();
        }
        
        return null;
    }

    public void updateMessage(Message m) {
        try {
            EntityManager em = util.getPersistenceFactory().createEntityManager();
            EntityTransaction tx = em.getTransaction();
            tx.begin();
            
            em.merge(m);
            
            tx.commit();
            em.close();
            
        } catch(Exception e) {
            System.out.println("Exception updating message: " + m.getMessageId());
            e.printStackTrace();
        }
    }
    
    public void deleteMessageById(int messageId) {
        try {
            EntityManager em = util.getPersistenceFactory().createEntityManager();
            EntityTransaction tx = em.getTransaction();
            tx.begin();
            
            
            em.createNativeQuery("delete from Message where messageId = :messageId")
                .setParameter("messageId", messageId)
                .executeUpdate();
                
            
            tx.commit();
            em.close();
            
        } catch(Exception e) {
            System.out.println("Exception deleteMessageById: " + messageId + " / ex: " + e.getMessage());
            e.printStackTrace();
        }
    }

    public void addMessage(Message m) {
        try {
            EntityManager em = util.getPersistenceFactory().createEntityManager();
            EntityTransaction tx = em.getTransaction();
            tx.begin();
                        
            em.persist(m);
            
            tx.commit();
            em.close();
            
        } catch(Exception e) {
            System.out.println("Exception in addMessage: " + e.getMessage());
            e.printStackTrace();
        }
    }

    
}


